package com.ydd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.dto.SYSRoleInsertDTO;
import com.ydd.dto.SYSRolePageQueryDTO;
import com.ydd.entity.SysRole;
import com.ydd.exception.BaseException;
import com.ydd.mapper.SysRoleMapper;
import com.ydd.mapper.SysRoleMenuMapper;
import com.ydd.result.PageResult;
import com.ydd.service.SysMenuService;
import com.ydd.service.SysRoleService;
import com.ydd.vo.RoleVO;
import com.ydd.vo.SysmenuVO;
import com.ydd.vo.common.MenuIdAndPid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Description TODO
 * @Author fang
 * @Date 2023-05-29 16:21
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 角色列表分页查询
     *
     * @param sysRolePageQueryDTO
     */
    @Override
    public PageResult<RoleVO> listRole(SYSRolePageQueryDTO sysRolePageQueryDTO) {
        Integer page = Integer.parseInt(sysRolePageQueryDTO.getPage());
        Integer limit = Integer.parseInt(sysRolePageQueryDTO.getLimit());
        PageHelper.startPage(page, limit);
        //条件查询角色
        Page<RoleVO> roleVOPage = sysRoleMapper.getRoleByQuery(sysRolePageQueryDTO);

        PageResult<RoleVO> pageResult = new PageResult<>();
        //总记录数
        pageResult.setCount(roleVOPage.getTotal());
        //当前页码
        pageResult.setCurrentPage(Integer.valueOf(sysRolePageQueryDTO.getPage()));
        //每页数量
        pageResult.setPageSize(roleVOPage.getPageSize());
        //总页数
        pageResult.setTotalPages(roleVOPage.getPages());

        for (RoleVO roleVO : roleVOPage) {
            //角色下的菜单列表：以逗号分隔
            String roleMenu = sysRoleMenuMapper.getRoleIdAndMenuId(roleVO.getId());
            roleVO.setRole_id(roleVO.getId());
            roleVO.setRole_menus(roleMenu);
        }
        //列表数据
        pageResult.setData(roleVOPage.getResult());
        return pageResult;
    }

    /**
     * 根据id查询角色详情
     *
     * @param id
     * @return
     */
    /*@Override
    public RoleVO rowInfo(String id) {
        //根据id查询角色的信息
        RoleVO roleVO = sysRoleMapper.rowInfo(id);
        //将id写入对象
        roleVO.setRole_id(id);
        //获取角色关联的菜单id，拼接成字符串，用逗号，分割
        String menuId = sysRoleMenuMapper.getRoleIdAndMenuId(id);
        //将菜单列表写入对象
        roleVO.setRole_menus(menuId);
        //根据角色id查询到菜单id和菜单父级Pid
        List<MenuIdAndPid> pids = sysRoleMenuMapper.getPidByRoleId(id);
        Integer min = Integer.MAX_VALUE;
        if (pids != null) {
            for (MenuIdAndPid mad : pids) {
                if(mad!=null){
                    if (mad.getPid() < min) {
                        min = mad.getPid();
                    }
                }
            }
        }
        List<SysmenuVO> sysmenuVOS = new ArrayList<>();
        if (min != -1) {
            for (MenuIdAndPid mad : pids) {
                if(mad!=null){
                    if (mad.getPid() == min) {
                        SysmenuVO sysmenuVO = sysMenuService.getMenuByIdAndPid(mad);
                        sysmenuVOS.add(sysmenuVO);
                    }
                }
            }
        }
        roleVO.setAuthList(sysmenuVOS);
        return roleVO;
    }*/
    @Override
    public RoleVO rowInfo(String id) {
        //根据id查询角色的信息
        RoleVO roleVO = sysRoleMapper.rowInfo(id);
        //将id写入对象
        roleVO.setRole_id(id);
        //获取角色关联的菜单id，拼接成字符串，用逗号，分割
        String menuId = sysRoleMenuMapper.getRoleIdAndMenuId(id);
        //将菜单列表写入对象
        if(menuId!=null){
            roleVO.setRole_menus(menuId);
        }
        //根据角色id查询到pid为0的菜单id与pid
        List<MenuIdAndPid> pids = sysRoleMenuMapper.getPidByRoleId(id);
        // 字符串数组存储id
        List<String> flag = sysRoleMenuMapper.getMenuIdByRoleId(id);
        //对pids进行排序，按照父级Pid的大小正序排序
        Comparator C = new Comparator<MenuIdAndPid>() {
            @Override
            public int compare(MenuIdAndPid o1, MenuIdAndPid o2) {
                return o1.getPid()-o2.getPid();
            }
        };
        if (pids != null) {
            Collections.sort(pids, C);
        }


        //按照pid的顺序递归查询
        List<SysmenuVO> sysmenuVOS = new ArrayList<>();
        for (MenuIdAndPid mad : pids) {//已经按照pid从小到大排过序了
            if (mad != null) {
                SysmenuVO sysmenuVO = sysMenuService.getMenuByIdAndPid(mad, flag);
                sysmenuVOS.add(sysmenuVO);
            }
        }
        roleVO.setAuthList(sysmenuVOS);
        return roleVO;
    }

    /**
     * 角色修改
     *
     * @param sysRoleInsertDTO
     */
    @Transactional
    @Override
    public void updateRole(SYSRoleInsertDTO sysRoleInsertDTO) {
        //获取角色的id
        String id = sysRoleMenuMapper.getRoleIdByName(sysRoleInsertDTO.getName());
        SysRole role = sysRoleMapper.getRoleById(id);
        //获取添加的新关联
        List<String> menuidsList = sysRoleInsertDTO.getMenuids();
        //先删除所有数据
        sysRoleMenuMapper.deleteMenuRoleById(id);
        //判断是否超级管理员
        if (role.getSuperadmin() == 1) {
            //把主要菜单添加回来
            sysRoleMenuMapper.addMenu();
            //获取菜单id串
            String roleIdAndMenuId = sysRoleMenuMapper.getRoleIdAndMenuId(id);
            //转为数组
            String[] split;
            if(roleIdAndMenuId!=null){
                split= roleIdAndMenuId.split(",");
                //遍历判断是否包含重复关联
                for (String s:split){
                    if (menuidsList.contains(s)){
                        menuidsList.remove(s);
                    }
                }
            }
        }

        if (menuidsList != null & menuidsList.size() > 0) {
            //sysRoleMenuMapper.deleteByMenuId();
            sysRoleMenuMapper.updateRoleMenu(menuidsList, id);
        }
        //sysRoleMenuMapper.updateRoleMenu(menuids, id);
        //修改角色表
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleInsertDTO, sysRole);
        sysRole.setUpdateDate(LocalDateTime.now());
        sysRole.setId(id);
        sysRoleMapper.updateRole(sysRole);
    }

    /**
     * 添加角色
     *
     * @param sysRoleInsertDTO
     */
    @Transactional
    @Override
    public void addRole(SYSRoleInsertDTO sysRoleInsertDTO) {
        SysRole sysRole = new SysRole();
        sysRole.setName(sysRoleInsertDTO.getName());
        sysRole.setDescription(sysRoleInsertDTO.getDescription());
        sysRole.setDelFlag("0");
        sysRole.setDefaultData("1");
        sysRole.setCreateDate(LocalDateTime.now());
        sysRole.setUpdateDate(LocalDateTime.now());
        sysRoleMapper.insert(sysRole);
        String Id = sysRole.getId();
        sysRoleMenuMapper.updateRoleMenu(sysRoleInsertDTO.getMenuids(), Id);
    }

    /**
     * 获取全部数据
     *
     * @return
     */
    @Override
    public List<RoleVO> allData() {
        List<RoleVO> list = sysRoleMapper.allData();
        return list;
    }

    /**
     * 删除角色
     *
     * @param id
     */
    @Transactional
    @Override
    public void delRole(String id) {
        if (id.equals("1c54e003c1fc4dcd9b087ef8d48abac3")) {
            throw new BaseException("不能删除当前登陆用户");
        } else {
            sysRoleMenuMapper.deleteMenuByRoleId(id);
            sysRoleMapper.delByRoleId(id);
        }
    }
}
